package log

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"os"
)

type BeeLogger struct {
	logger *logs.BeeLogger
	Logger
}

func (log *BeeLogger) SetServiceName(serviceName string) {

}

func (log *BeeLogger) SetLevel(level string) {
	switch level {
	case "debug":
		log.logger.SetLevel(logs.LevelDebug)
	case "info":
		log.logger.SetLevel(logs.LevelInfo)
	case "error":
		log.logger.SetLevel(logs.LevelError)
	case "alert":
		log.logger.SetLevel(logs.LevelAlert)
	case "warn":
		log.logger.SetLevel(logs.LevelWarn)
	}
}

func (log *BeeLogger) Trace(msg string, appends ...map[string]interface{}) {
	log.logger.Trace(msg, appends)
}

func (log *BeeLogger) Debug(msg string, appends ...map[string]interface{}) {
	appendsJson, _ := json.Marshal(appends)
	if appendsJson == nil {
		logs.Debug(msg, make(map[string]interface{}, 0))
	} else {
		var out bytes.Buffer
		err := json.Indent(&out, appendsJson, "", "  ")
		if err != nil {
			fmt.Println(msg)
			return
		}
		logs.Debug(msg, out.String())
	}
}

func (log *BeeLogger) Info(msg string, appends ...map[string]interface{}) {
	appendsJson, _ := json.Marshal(appends)
	if appendsJson == nil {
		logs.Info(msg, make(map[string]interface{}, 0))
	} else {
		var out bytes.Buffer
		err := json.Indent(&out, appendsJson, "", "  ")
		if err != nil {
			fmt.Println(msg)
			return
		}
		logs.Info(msg, out.String())
	}
}

func (log *BeeLogger) Error(msg string, appends ...map[string]interface{}) {
	appendsJson, _ := json.Marshal(appends)
	if appendsJson == nil {
		logs.Info(msg, make(map[string]interface{}, 0))
	} else {
		var out bytes.Buffer
		err := json.Indent(&out, appendsJson, "", "  ")
		if err != nil {
			fmt.Println(msg)
			return
		}
		logs.Error(msg, out.String())
	}
}

func (log *BeeLogger) Warn(msg string, appends ...map[string]interface{}) {
	log.logger.Warn(msg, appends)
}

func (log *BeeLogger) Panic(msg string, appends ...map[string]interface{}) {
	log.logger.Error(msg, appends)
}

type LoggerConfig struct {
	Level      int    `json:"level,omitempty"`
	Filename   string `json:"filename,omitempty"`
	MaxSize    int    `json:"maxsize,omitempty"`
	MaxBackups int    `json:"max_backups,omitempty"`
	MaxAge     int    `json:"max_age,omitempty"`
	Compress   bool   `json:"compress,omitempty"`
}

func NewBeeLogger() *BeeLogger{
	logger := logs.GetBeeLogger()
	if os.Getenv("LOG_FILE") == "true" {
		confByte, _ := json.Marshal(LoggerConfig{
			Filename: "debug.log",
			Level:    7,
			MaxSize:  1024 * 1024 * 2,
		})
		err := logger.SetLogger(logs.AdapterFile, string(confByte))
		if err != nil {
			fmt.Println(err.Error())
			return nil
		}
	} else {
		err := logger.SetLogger(logs.AdapterConsole, `{"level":7,"color":true}`)
		if err != nil {
			fmt.Println(err.Error())
			return nil
		}
	}
	//logger.SetPrefix(constant.SERVICE_NAME)
	logger.EnableFuncCallDepth(true)
	logger.SetLogFuncCallDepth(5)
	return &BeeLogger{
		logger: logger,
	}
}
